<?php
/**
 * 后台主页控制器
 * Created by PhpStorm.
 * User: change
 * Date: 2016/12/22
 * Time: 22:17
 */

namespace Admin\Controller;

use Admin\Model\AdminUserModel;
use Base\Controller\BaseAdminController;
use Think\Controller;
use Think\Verify;

class IndexController extends BaseAdminController
{
    public function index()
    {
        if ($this->isLogin()) {
            $this->redirect('Control/index');
        } else {
            $this->redirect('login');
        }
    }

    /**
     * 后台登录
     * @param string $act
     */
    public function login($act = '')
    {
        if ($this->isLogin()) {
            $this->success('已经登录', U('Control/index'));
        }
        switch ($act) {
            case 'login':
                $name = I('post.user_name');
                $pwd = I('post.user_pass');
                if (empty($name) || empty($pwd)){
                    $this->error('用户名或者密码不能为空');
                }
                if (!$this->checkVerify(I('post.verify'))) {
                    $this->error('验证码不正确');
                }
                $userModel = new AdminUserModel();
                $userName = $userModel->where(array('name'=>$name))->getField('id');
                if (empty($userName)){
                    $this->error('用户名不存在');
                }
                $user = $userModel->login($name,$pwd);
                if (!empty($user)) {
                    session('user', $user);
                    $this->success('登录成功', U('Control/index'));
                } else {
                    $this->error('用户名或者密码错误');
                }
                break;
            default:
                //登录视图
                $this->show('');
                break;
        }
    }

    /**
     * 验证码
     */
    public function verify()
    {
        $config = array(
            'imageW' => '150',
            'imageH' => '40',
            'fontSize' => 20,
            'length' => 4,
            'useNoise' => false,
            'useCurve' => false,
            'codeSet' => '0123456789',
        );
        ob_clean();
        $verify = new Verify($config);
        $verify->entry();
    }

    /**
     * 验证码是否正确
     * @param $code
     * @param string $id
     * @return bool
     */
    function checkVerify($code, $id = '')
    {
        $verify = new Verify();
        return $verify->check($code, $id);
    }

}